import React, { useCallback, useMemo, useState } from 'react';
import VoteFooter from './voteFooter';
import VoteMain from './voteMain';

const Vote = () => {
    let [state, setState] = useState({
        upNum: 0,
        downNum: 0,
    })
    let total = useMemo(() => {
        return state.upNum + state.downNum
    }, [state.upNum, state.downNum])
    let rate = useMemo(() => {
        let rate = state.upNum / (state.upNum + state.downNum)
        return Object.is(rate, NaN) ? '-' : (rate * 100).toFixed(2) + '%'
    }, [state.upNum])
    // 缓存函数useCallback，但需要传入依赖项，否则数据因为闭包不更新
    const change = useCallback((type) => {
        if (type === 'up') {
            setState({
                ...state,
                upNum: state.upNum + 1
            })
            return
        }
        setState({
            ...state,
            downNum: state.downNum + 1
        })
    },[state])
    return (
        <div>
            <h4>投票</h4>
            <p>总人数:{total}</p>
            <p>支持率:{rate}</p>
            <VoteMain state={state} />
            <VoteFooter change={change} />
        </div>
    );
};
export default Vote;
